package cn.fengsweb.tokyotyrant
{
	import cn.fengsweb.tokyotyrant.define.TokyoTyrantConnectionStatusType;
	
	import flash.utils.ByteArray;

	internal class AbstractHandler
	{
		protected var _host:String;
		protected var _port:uint;
		
		protected var _ttc:TokyoTyrantConnection;
		protected var _ttr:TokyoTyrantResponder;
		
		private var _successHandler:Function;
		private var _failedHandler:Function;
		
		public function AbstractHandler(host:String, port:uint)
		{
			_host	= host;
			_port	= port;
		}
		
		protected function defaultHandler(sendBytes:ByteArray, successHandler:Function, failedHandler:Function=null):void
		{
			if(null == _ttr){
				_ttc.connect(sendBytes);
			}else{
				_ttc.connect(sendBytes, defaultFeedback);
			}
			
			_successHandler	= successHandler;
			_failedHandler	= failedHandler;
		}
		
		private function defaultFeedback(type:uint, recvBytes:ByteArray=null):void
		{
			if(0 == type){
				var code:int	= recvBytes.readByte();
				if(0 == code){
					_successHandler(recvBytes);
				}else{
					if(null == _failedHandler){
						_ttr.result(null);
					}else{
						_failedHandler();
					}
				}
			}else{
				if(null != _ttr.status){
					_ttr.status(TokyoTyrantConnectionStatusType.TOKYO_TYRANT_QUERY_FAILED);
				}
			}
		}
	}
}